
package jh.com.jhappbf.weight.query;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.fragment.AbFragment;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.SettingModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.ExpressionUtils;
import jh.com.jhappbf.utils.FileImport;
import jh.com.jhappbf.utils.JsonHelper;

/**
 * @author Administrator
 */
public class QueryWeightListView extends AbFragment {

    private List<JSONObject> mShowData = new ArrayList<>(); //列表显示的数据
    private List<JSONObject> mDataSource = new ArrayList<>(); //数据源
    private MyBaseAdapter mAdapter; //数据列表适配器
    private AbLoadDialogFragment mDialogFragment = null; //进度框
    private List<String> mFields = new ArrayList<>();
    private List<String> mSaverFields = new ArrayList<>();
    private int mCurrentScreenWidth = 80;//默认列表宽度
    private Drawable mLeftDrawable; //列表单元格边框
    private Drawable mHeadDrawable;//列表头下拉框
    private int mCurrentPage = 0;//当前页数
    private int mPageSize = 100; //当前页的大小
    private Context mAppContext;
    private AbPullToRefreshView mRefreshView; // 下拉刷新上拉加载更多
    private LinearLayout mListViewHeader; // 数据标题
    private ListView mListView; // 数据列表
    private RelativeLayout mErrorContentView; // 网络不给力显示的视图
    private RelativeLayout mContentView; // 显示的数据列表的视图
    private Button mBtnErrRefresh; // 重试
    private Button mBtnSetting; // 设置
    private List<TextView> mTitleTxt = new ArrayList<>(); //列表的表头view
    private final int SETTING = 0X001;
    private String mFlag = "";
    private SettingModel mSettingModel;
    private ArrayList<String> mSelectData = new ArrayList<>();
    private List<JSONObject> newListData = new ArrayList<>();
    private RelativeLayout mExportExcel;
    private Map<String, String> mFieldsMap;
    private String methodName = "queryWeight";
    private ArrayList<String> param;
    private ArrayList<String> value;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Intent i = getActivity().getIntent();
        if (i != null) {
            mFlag = i.getStringExtra("flag");
            mSettingModel = i.getParcelableExtra("data");
        }
        View v = inflater.inflate(R.layout.query_weight_listview_activity, null);
        initView(v);
        return v;
    }

    /**
     * 初始化
     */
    private void initView(View v) {

        param = new ArrayList<>();
        value = new ArrayList<>();
        mAppContext = getActivity();
        mFieldsMap = new LinkedHashMap<>();
        mFieldsMap.put("序号", "orderNum");
        mFieldsMap.put("编号", "id");
        mFieldsMap.put("车号", "Platenumber");
        mFieldsMap.put("类型", "Type");
        mFieldsMap.put("货名", "Cargoname");
        mFieldsMap.put("等级", "Specification");
        mFieldsMap.put("合同单位", "S9");
        mFieldsMap.put("发货", "Consignor");
        mFieldsMap.put("收货", "Consignee");
        mFieldsMap.put("产地", "S4");
        mFieldsMap.put("毛重", "Gross");
        mFieldsMap.put("皮重", "Tare");
        mFieldsMap.put("净重", "Net");
        mFieldsMap.put("单价", "Price");
        mFieldsMap.put("金额", "Amount");
//        mFieldsMap.put("日期", "sDate");
//        mFieldsMap.put("时间", "sTime");
        mFieldsMap.put("毛重时间", "GrossTime");
        mFieldsMap.put("皮重时间", "TareTime");

        for (Entry<String, String> entry : mFieldsMap.entrySet()) {
            mFields.add(entry.getKey());
            mSaverFields.add(entry.getValue());
        }

        WindowManager wm = getActivity().getWindowManager();
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
//		mCurrentScreenWidth =60;// (metrics.widthPixels)/(10 + 1);
        mLeftDrawable = ContextCompat.getDrawable(getActivity(), R.mipmap.table_line);
        mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(), mLeftDrawable.getMinimumHeight());
        mHeadDrawable = ContextCompat.getDrawable(getActivity(), R.mipmap.down_select);
        mHeadDrawable.setBounds(0, 0, mHeadDrawable.getMinimumWidth(), mHeadDrawable.getMinimumHeight());

        mContentView = v.findViewById(R.id.query_weight_content);
        mErrorContentView = v.findViewById(R.id.query_weight_error_view);
        mRefreshView = v.findViewById(R.id.query_pullToRefreshView);
        mListView = v.findViewById(R.id.query_listView);
        mListViewHeader = v.findViewById(R.id.query_weight_title);
        mBtnErrRefresh = v.findViewById(R.id.query_weight_error_btn);
        mBtnSetting = getActivity().findViewById(R.id.title_right_btn);
        mExportExcel = v.findViewById(R.id.query_weight_export_excel_layout);
        // 重试
        mBtnErrRefresh.setOnClickListener(v1 -> loadFirst());

        mExportExcel.setOnClickListener(view -> {
//            String url = Constant.ServerPath + "outPutFile/query/" + State.mAccount + "查询.xls";
//            new ExportHelper(mDialogFragment, url, getActivity(), "查询").export();

            boolean result = FileImport.generateExcel("查询报表", mShowData, mSaverFields, mFields);
            if (result) {
                Toast.makeText(mAppContext, "导出成功", Toast.LENGTH_SHORT).show();
            }
        });

        // 设置
        mBtnSetting.setOnClickListener(v12 -> {
            Intent i = new Intent(getActivity(), QuerySetting.class);
            i.putExtra("data", mSettingModel);
            startActivityForResult(i, SETTING);
        });

        // 下拉刷新
        mRefreshView.setOnHeaderRefreshListener(view -> refreshTask(mSettingModel));

        // 上拉加载更多
        mRefreshView.setOnFooterLoadListener(view -> loadMoreTask(mSettingModel));

        // 单击数据项
        mListView.setOnItemClickListener((parent, view, position, id) -> {
        });

        //长按列表显示称重的详细信息
        mListView.setOnItemLongClickListener((parent, view, position, id) -> {
            Intent i = new Intent(getActivity(), QueryWeightDetail.class);
            JSONObject obj = mShowData.get(position);
            String weightId = obj.optString("id");
            i.putExtra("flag", weightId);
            startActivity(i);
            return true;
        });

        // 设置进度条的样式
        mRefreshView.getHeaderView().setHeaderProgressBarDrawable(
                ContextCompat.getDrawable(getActivity(), R.drawable.progress_circular));
        mRefreshView.getFooterView().setFooterProgressBarDrawable(
                ContextCompat.getDrawable(getActivity(), R.drawable.progress_circular));

        // 生成数据列表表头
        makeHeader();

        // 加载数据
        loadFirst();

        // 绑定ListView的Adapter
        mAdapter = new MyBaseAdapter();
        mListView.setAdapter(mAdapter);
    }

    /**
     * 第一次加载
     */
    private void loadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(getActivity(), R.mipmap.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> {
            mErrorContentView.setVisibility(View.GONE);
            mContentView.setVisibility(View.VISIBLE);
            refreshTask(mSettingModel);
        });
    }

    /**
     * 制作表头
     */
    private void makeHeader() {
        TableLayout table = new TableLayout(mAppContext);
        TableRow row = new TableRow(mAppContext);
        String columnName;
        for (int index = 0; index < mFields.size(); index++) {
            TextView txt = new TextView(getActivity());
            setColumnWidth(mFields.get(index), txt);
            txt.setTextColor(Color.BLACK);
            txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
            txt.setGravity(Gravity.CENTER);
            txt.setPadding(1, 10, 0, 10);
            txt.setId(index);
            columnName = mFields.get(index);
            txt.setText(columnName);
            txt.setTag(columnName);
            txt.setClickable(true);
            mTitleTxt.add(txt);
            txt.setOnClickListener(this::popupWindow);
            txt.setCompoundDrawables(mLeftDrawable, null, null, null);
            txt.setCompoundDrawables(null, null, mHeadDrawable, null);
            row.addView(txt);
        }
        table.addView(row);
        mListViewHeader.addView(table);
    }

    private void setColumnWidth(String columnName, TextView textView) {
        switch (columnName) {
            case "货名":
            case "车号":
            case "类型":
                textView.setWidth((int) (mCurrentScreenWidth * 2.5));
                break;
            case "发货":
            case "收货":
                textView.setWidth((int) (mCurrentScreenWidth * 3.5));
                break;
            case "原发净重":
            case "实收净重":
                textView.setWidth(mCurrentScreenWidth * 3);
                break;
            case "毛重时间":
            case "皮重时间":
            case "合同单位":
                textView.setWidth(mCurrentScreenWidth * 4);
                break;
            default:
                textView.setWidth(mCurrentScreenWidth * 2);
                break;
        }
    }


    /**
     * 弹出选择框
     *
     * @param v 当前View
     */
    private void popupWindow(View v) {
        if (v instanceof TextView) {
            final TextView txt = (TextView) v;
            String columnName = (String) txt.getTag();
            String columnField = mFieldsMap.get(columnName);
            if (!TextUtils.isEmpty(columnField)) {
                mSelectData.clear();
                mSelectData.add(columnName);
                String item;
                for (JSONObject jsonObject : mDataSource) {
                    item = jsonObject.optString(columnField);
                    if (!mSelectData.contains(item)) {
                        mSelectData.add(item);
                    }
                }
                new AlertDialog.Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                        .setTitle(columnName + "选择")
                        .setItems(mSelectData.toArray(new String[0]), (dialog, which) -> {
                            txt.setText(mSelectData.get(which));
                            filterData();
                        }).create().show();
            }
        }
    }

    /**
     * 过滤数据源
     */
    private void filterData() {
        String valStr;
        String tagStr;
        Map<String, String> mHashMap = new HashMap<>();
        for (TextView txt : mTitleTxt) {
            valStr = txt.getText().toString();
            tagStr = (String) txt.getTag();
            if (!valStr.equals(tagStr)) {
                mHashMap.put(tagStr, valStr);
            }
        }
        if (mHashMap.size() > 0) {
            mShowData = new ArrayList<>();
            JSONObject mObject;
            float gross = 0;
            float tare = 0;
            float net = 0;
            for (int index = 0; index < mDataSource.size(); index++) {
                mObject = mDataSource.get(index);
                for (Entry<String, String> entry : mFieldsMap.entrySet()) {
                    if (mHashMap.containsKey(entry.getKey())) {
                        if (mObject.optString(entry.getValue()).equals(entry.getKey())) {
                            String grossStr = mObject.optString("Gross");
                            String tareStr = mObject.optString("Tare");
                            String netStr = mObject.optString("Net");
                            String plateNumber = mObject.optString("Platenumber");
                            if (!"合计".equals(plateNumber)) {
                                if (ExpressionUtils.isNumber(grossStr)) {
                                    gross += Float.parseFloat(grossStr);
                                }
                                if (ExpressionUtils.isNumber(tareStr)) {
                                    tare += Float.parseFloat(tareStr);
                                }
                                if (ExpressionUtils.isNumber(netStr)) {
                                    net += Float.parseFloat(netStr);
                                }
                            }
                            mShowData.add(mObject);
                        }
                    }
                }
            }
            try {
                JSONObject sumObject = new JSONObject();
                sumObject.put("Platenumber", "合计");
                sumObject.put("Cargoname", "车数:" + mShowData.size());
                sumObject.put("Specification", "");
                DecimalFormat format = new DecimalFormat("0.00");
                sumObject.put("Gross", format.format(gross));
                sumObject.put("Tare", format.format(tare));
                sumObject.put("Net", format.format(net));
                mShowData.add(sumObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mAdapter.notifyDataSetChanged();
        } else {
            mShowData = mDataSource;
            getSum();
            mAdapter.notifyDataSetChanged();
        }
    }

    ///总合计
    private void getSum() {
        JSONObject obj;
        float net = 0;
        float gross = 0;
        float tare = 0;
        for (int index = 0; index < mShowData.size(); index++) {
            obj = mShowData.get(index);
            String netStr = obj.optString("Net");
            String grossStr = obj.optString("Gross");
            String tareStr = obj.optString("Tare");
            if (obj.optString("Platenumber").contains("合计")) {
                continue;
            }
            if (ExpressionUtils.isNumber(netStr)) {
                net += Float.parseFloat(netStr);
            }
            if (ExpressionUtils.isNumber(grossStr)) {
                gross += Float.parseFloat(grossStr);
            }
            if (ExpressionUtils.isNumber(tareStr)) {
                tare += Float.parseFloat(tareStr);
            }
        }
        try {
            JSONObject sumObject = new JSONObject();
            sumObject.put("Platenumber", "合计");
            if (mCurrentPage == 1) {
                sumObject.put("Cargoname", "记录数:" + (mShowData.size()));
            } else if (mCurrentPage == 2 && newListData.size() == mPageSize) {
                sumObject.put("Cargoname", "记录数:" + (mShowData.size()));
            } else {
                sumObject.put("Cargoname", "记录数:" + (mShowData.size() - 1));
            }
            sumObject.put("Specification", "");
            DecimalFormat format = new DecimalFormat("0.00");
            sumObject.put("Net", format.format(net));
            sumObject.put("Gross", format.format(gross));
            sumObject.put("Tare", format.format(tare));
            if (mShowData.size() > 0) {
                JSONObject firstObj = mShowData.get(0);
                String val = firstObj.getString("Platenumber");
                if (val.contains("合计")) {
                    mShowData.remove(0);
                }
                mShowData.add(0, sumObject);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void initRequestParams(SettingModel model) {
        param.clear();
        value.clear();
        methodName = "queryWeight";
        param.add("currentPage");
        param.add("startDateTime");
        param.add("endDateTime");
        param.add("cargoname");
        param.add("platenumber");
        param.add("sender");
        param.add("receiver");
        param.add("sitePoint");
        param.add("types");
        param.add("users");
        param.add("admin");
        value.add(Integer.toString(mCurrentPage));
        if (model == null) {
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add("");
        } else {
            value.add(model.getStartDateTime());
            value.add(model.getEndDateTime());
            value.add(model.getCargoname());
            value.add(model.getPlatenumber());
            value.add(model.getSender());
            value.add(model.getReceiver());
            value.add(model.getSitePoint());
        }
        switch (mFlag) {
            case "buy"://销售查询
                value.add("采购");
                break;
            case "sale":
                value.add("销售");
                break;
            case "out":
                value.add("零售");//零售查询
                break;
            default:
                value.add("");
                break;
        }
        value.add(State.mAccount + "查询");
        if (State.mRight.contains("admin") || "gys".equals(State.mAccount)) {
            value.add("admin");
        } else {
            value.add("normal");
        }
    }
    /**
     * 下拉刷新
     */
    private void refreshTask(SettingModel model) {
        mCurrentPage = 1;
        initRequestParams(model);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(getActivity());
            mRefreshView.onHeaderRefreshFinish();
            mErrorContentView.setVisibility(View.GONE);
            mContentView.setVisibility(View.VISIBLE);
            newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null) {
                mDataSource.clear();
                mDataSource.addAll(newListData);
                if (mDataSource.size() > 0) {
                    if (mDataSource.size() >= mPageSize) {
                        mCurrentPage++;
                    }
                    filterData();
                }
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(getActivity());
            mRefreshView.onHeaderRefreshFinish();
            mErrorContentView.setVisibility(View.VISIBLE);
            mContentView.setVisibility(View.GONE);
            mShowData.clear();
            mAdapter.notifyDataSetChanged();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    /**
     * 上拉加载更多
     */
    private void loadMoreTask(SettingModel model) {
        initRequestParams(model);
        Listener<String> listener = response -> {
            mRefreshView.onFooterLoadFinish();
            if (newListData.size() > 0 && newListData.size() < mPageSize) {
                if (mCurrentPage == 1) {
                    mDataSource.remove(0);
                }
                mDataSource.removeAll(newListData);
            }
            newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                mDataSource.addAll(newListData);
                if (newListData.size() == mPageSize) {
                    mCurrentPage++;
                }
                filterData();
            }
        };
        ErrorListener errorListener = error -> {
            mRefreshView.onFooterLoadFinish();
            AbToastUtil.showToast(mAppContext, "数据加载失败！");
        };
        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETTING && data != null) {
            mSettingModel = data.getParcelableExtra("result");
            if (mSettingModel != null) {
                loadFirst();
            }
        }
    }

    private class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mShowData.size();
        }

        @Override
        public Object getItem(int position) {

            return mShowData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            TableLayout table;
            if (convertView == null) {
                Context context = getActivity();
                table = new TableLayout(context);
                TableRow row = new TableRow(context);
                Drawable mItemSelect = ContextCompat.getDrawable(getActivity(), R.drawable.list_item_bg);
                row.setBackground(mItemSelect);
                row.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
                for (int index = 0; index < mFields.size(); index++) {
                    TextView textView = new TextView(getActivity());
                    setColumnWidth(mFields.get(index), textView);
                    textView.setTextColor(Color.BLACK);
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
                    textView.setGravity(Gravity.CENTER);
                    textView.setPadding(1, 0, 1, 0);
                    textView.setId(index);
                    textView.setCompoundDrawables(mLeftDrawable, null, null, null);
                    row.addView(textView);
                }
                table.addView(row);
                convertView = table;
                convertView.setTag(table);
            } else {
                table = (TableLayout) convertView.getTag();
            }
            JSONObject obj = mShowData.get(position);
            int length = mSaverFields.size();
            //显示表格的一行数据
            for (int i = 0; i < length; i++) {
                TextView textView = table.findViewById(i);
                if (i == 0) {
                    textView.setText(position + "");
                } else {
                    textView.setText(obj.optString(mSaverFields.get(i)));
                }
            }
            return convertView;
        }
    }
}